<script lang="ts" setup>
import { ref, reactive, defineEmits } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormRules, FormInstance } from 'element-plus'
import * as PwdApi from '@/api/password'
import { useUserStore } from '@/store/modules/user'
import { useTagsViewStore } from '@/store/modules/tagsView'
const message = useMessage() // 消息弹窗
defineOptions({ name: 'PwdReset' })
const { replace } = useRouter()

const tagsViewStore = useTagsViewStore()
const userStore = useUserStore()
const { t } = useI18n()
const userName = computed(() => userStore.user.username ?? '')
const passwordStatus = computed(() => userStore.user.passwordStatus ?? 0)

const ruleFormRef = ref<FormInstance>()
// 用户名找回
interface RuleForm {
  oldPassword: string
  newPassword: string
  password2: string
}

const formData = reactive<RuleForm>({
  oldPassword: '',
  newPassword: '',
  password2: ''
})

const validatePass = (rule: any, value: any, callback: any) => {
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,16}$/
  if (value === '') {
    callback(new Error(t('forget.phPwd2')))
  } else if (!passwordRegex.test(value)) {
    callback(new Error(t('forget.errPwdTip')))
  } else {
    callback()
  }
}

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error(t('forget.phPwd2')))
  } else if (value !== formData.newPassword) {
    callback(new Error(t('forget.errPwdTip2')))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<RuleForm>>({
  // id: [
  //   { required: true, message: '', trigger: 'blur' },
  //   { min: 1, max: 50, message: '', trigger: 'blur' },
  // ],
  oldPassword: [
    { required: true, message: t('profile.password.oldPwdMsg'), trigger: 'blur' }
    // { min: 8, max: 16, message: t('profile.password.pwdRules'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('profile.password.newPwdMsg'), trigger: 'blur' },
    // { min: 1, max: 50, message: '', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  password2: [
    { required: true, message: t('profile.password.cfPwdMsg'), trigger: 'blur' },
    { min: 8, max: 16, message: t('forget.errPwdTip'), trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
})

// methods
const isSubmitting = ref(false)
const emit = defineEmits(['destroy'])
const handleDestory = () => {
  emit('destroy', {})
}

const handleResetPwdById = async (formEl: FormInstance | undefined) => {
  isSubmitting.value = true
  try {
    if (!formEl) return
    const valid = await formEl.validate()
    if (valid) {
      try {
        const result = await PwdApi.resetPwdById(formData)
        if (result) {
          message.success(t('common.updateSuccess'))
          setTimeout(async () => {
            await userStore.loginOut()
            tagsViewStore.delAllViews()
            replace('/login?redirect=/index')
            // 退出系统
          }, 3000)
        }
      } catch (e) {
        console.log(e)
      }
    }
  } catch (e) {
    console.log(e)
  }
  isSubmitting.value = false
}
</script>
<template>
  <div class="pwd-reset">
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="auto"
      label-position="right"
    >
      <!-- 需求，只有第一次提示重置密码时，显示 -->
      <div class="first-init-pwd-tip" v-if="passwordStatus == 1">
        {{ t('forget.resetPwdTitle') }}
      </div>
      <el-form-item :label="t('forget.labelId')" prop="id">
        {{ userName }}
      </el-form-item>
      <el-form-item :label="t('forget.labelCurrentPwd')" prop="oldPassword">
        <el-input
          v-model="formData.oldPassword"
          :placeholder="t('forget.phPwd')"
          type="password"
          show-password
          autocomplete="new-password"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item :label="t('forget.labelPwd')" prop="newPassword">
        <el-input
          v-model="formData.newPassword"
          :placeholder="t('forget.phPwd')"
          type="password"
          show-password
          autocomplete="new-password"
          maxlength="16"
        />
      </el-form-item>
      <el-form-item :label="t('forget.labelPwd2')" prop="password2">
        <el-input
          v-model="formData.password2"
          :placeholder="t('forget.phPwd2')"
          type="password"
          show-password
          autocomplete="new-password"
          maxlength="16"
        />
      </el-form-item>
      <el-form-item>
        <div class="form-footer">
          <el-button round @click="handleDestory">{{ t('forget.txtCancel') }}</el-button>
          <el-button
            type="primary"
            round
            :loading="isSubmitting"
            @click="handleResetPwdById(ruleFormRef)"
            >{{ t('forget.txtSubmit') }}</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss">
.dark {
  .pwd-reset {
    svg {
      color: #fff;
    }
  }
}
.pwd-reset {
  .el-input__icon {
    width: 18px;
    height: 16px;

    svg {
      width: 100%;
      height: 100%;
    }
  }

  .el-form-item__error {
    margin-top: 14px;
    position: relative;
    font-size: 14px;
    top: 0;
  }
}
</style>
<style lang="scss" scoped>
.pwd-reset {
  margin: 0px -16px;
  padding: 16px 24px 0;
  border-top: solid 1px rgba(255, 255, 255, 0.1);
  .first-init-pwd-tip {
    font-weight: 400;
    font-size: 14px;
    color: #fa5959;
    margin-bottom: 10px;
  }
  .form-footer {
    display: flex;
    justify-content: end;
    width: 100%;

    .el-button {
      width: 80px;
    }
  }

  .input-sms-code {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }
}
</style>
